package com.gitee.wsl.jvm.okhttp.intercept.base

import okhttp3.Interceptor
import okhttp3.Response
import timber.log.Timber
import java.io.IOException


/**
 *
 * 描述：设置缓存功能
 */
open class CacheHeaderSettingInterceptor(
    maxTimeStale:Int= MAX_STALE,
    maxTimeStaleOnline:Int= MAX_STALE_ONLINE,
    var cacheControlValue_Offline: String = String.format("max-age=%d", maxTimeStaleOnline),
    var cacheControlValue_Online: String = String.format("max-age=%d", maxTimeStale)
) : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalResponse: Response = chain.proceed(chain.request())
        val cacheControl = originalResponse.header("Cache-Control")
        Timber.e(MAX_STALE_ONLINE.toString() + "s load cache:" + cacheControl)
        return if (cacheControl?.isEmpty() == true || cacheControl!!.contains("no-store") || cacheControl.contains("no-cache") ||
            cacheControl.contains("must-revalidate") || cacheControl.contains("max-age") || cacheControl.contains(
                "max-stale"
            )
        ) {
            originalResponse.newBuilder()
                .removeHeader("Pragma")
                .removeHeader("Cache-Control")
                .header("Cache-Control", "public, max-age=$MAX_STALE")
                .build()
        } else {
            originalResponse
        }
    }

    companion object {
        //set cahe times is 3 days
         const val MAX_STALE = 60 * 60 * 24 * 3

        // read from cache for 60 s
         const val MAX_STALE_ONLINE = 60
    }
}